package ru.dirty.android;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.*;

import java.io.IOException;
import java.util.ArrayList;

public class PostSelected extends Activity{
    private String imgUrl;
	protected CommentsListAdapter adapter;
	private int postID;
	private Button expandComments;
	private ProgressBar commentsLoadingBar;
	private ImageView commentsAttention;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //make app without title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.selectedpost);

    	ListView list;
        list = (ListView)findViewById(R.id.postListView);
        View headerView;
        ViewGroup headerViewOriginal = (ViewGroup) findViewById(R.id.headerLayout);
        headerView = this.getLayoutInflater().inflate(R.layout.post_header_layout,headerViewOriginal);

        ImageButton share = (ImageButton)headerView.findViewById(R.id.share);
        ImageButton openPost = (ImageButton)headerView.findViewById(R.id.browser);
        final ImageButton img = (ImageButton)headerView.findViewById(R.id.postImage);
        commentsAttention = (ImageView)headerView.findViewById(R.id.commentsAttention);
        TextView header = (TextView)headerView.findViewById(R.id.header);
        TextView text = (TextView)headerView.findViewById(R.id.text);
        TextView rating = (TextView)headerView.findViewById(R.id.rating);
        TextView autor = (TextView)headerView.findViewById(R.id.autor);
        ImageView stars = (ImageView)headerView.findViewById(R.id.stars);
        expandComments = (Button)headerView.findViewById(R.id.expandComments);
        commentsLoadingBar = (ProgressBar)headerView.findViewById(R.id.commentsLoading);

        ImageLoader asyncImageLoader;
        asyncImageLoader = new ImageLoader(getBaseContext());
        Bundle extras = getIntent().getExtras(); 
        imgUrl = extras.getString("imgUrl");
        
        String sRating = extras.getString("rating");
        String sAutor = extras.getString("autor");
        boolean starsFlag = extras.getBoolean("stars");
        String sHeader = extras.getString("header");
        String txt=extras.getString("text");
        postID = extras.getInt("postID");
        
        if(imgUrl == null)
        	img.setVisibility(View.GONE);
        else
        {
        	Resources r = getResources();
        	if(imgUrl.contains(getString(R.string.youtubeAdressImg)))
        	{
                img.setTag(1);
                txt = txt.substring(13);               //TODO:
                asyncImageLoader.postDisplayImage(imgUrl, r ,img);
        		img.setScaleType(ImageView.ScaleType.FIT_XY);
        		final float scale = r.getDisplayMetrics().density;
        		int width = (int) (180 * scale + 0.5f);
        		int height = (int) (135 * scale + 0.5f);
        		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)img.getLayoutParams();
                params.width = width;
                params.height = height;
        		img.setLayoutParams(params);
                headerView.findViewById(R.id.youtube_icon).setVisibility(View.VISIBLE);
        	}
        	else{
                img.setTag(1);
        		asyncImageLoader.DisplayImage(imgUrl,img,false);
            }
        	img.setVisibility(View.VISIBLE);
        }
        if(sHeader == null)
        	header.setVisibility(View.GONE);
        else
        {
        	header.setVisibility(View.VISIBLE);
        	header.setText(sHeader);
        }
        Log.w("header text:",txt);
        Spanned spanHtml = Html.fromHtml(txt);
    	text.setText(spanHtml);
    	text.setMovementMethod(LinkMovementMethod.getInstance());
    	rating.setText(sRating);
    	autor.setText(sAutor);
    	
    	if(starsFlag)
    	{
    		stars.setVisibility(View.VISIBLE);
    		RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
    		        ViewGroup.LayoutParams.WRAP_CONTENT);

    		p.addRule(RelativeLayout.BELOW, R.id.rating);
    		p.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

    		autor.setLayoutParams(p);
    		

    	}
    	else
    		stars.setVisibility(View.GONE);

    	OnClickListener buttonsListen = new OnClickListener() {
    		private boolean flag=true;
    		private InitTask initTask = new InitTask();;
    	        public void onClick(View v) {
    	            switch(v.getId())
    	            {
    	            	case R.id.postImage:
		    	        	if(imgUrl.contains(getString(R.string.youtubeAdressImg)))
		    	        	{
		    	        		String youtubeID = imgUrl.substring(imgUrl.indexOf("/vi/")+4, imgUrl.length()-6);
		    	        		//Log.w("PostSelected",youtubeID);
		    	        		startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.youtubeVideo)+youtubeID)));
		    	        	}
		    	        	else
		    	        	{
		
		    	        		/*Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(
		    	        		  imgUrl));
		    	        		startActivity(intent);*/
		    	        		
		    	        		Intent intent = new Intent();
		    	        		intent.setAction(Intent.ACTION_VIEW);
		    	        		intent.setDataAndType(Uri.parse("file://" + "/sdcard/dirtyReader/"+imgUrl.hashCode()), "image/*");
		    	        		startActivity(intent);

		                	}
		    	        	break;
    	            	case R.id.expandComments:
    	              		if(initTask.getStatus()!=AsyncTask.Status.RUNNING)
	    	            	{	if(flag){
		    	            		expandComments.setText(getString(R.string.hide_comments));
		    	            		initTask = new InitTask();
		    	            		initTask.execute(getString(R.string.dirtyComments)+Integer.toString(postID));
		    	               	 	flag = false;
	    	            		}
	    	            		else{
	    	                    	commentsAttention.setVisibility(View.GONE);
	    	                    	adapter.clear();
		                    		adapter.notifyDataSetChanged();
		                    		expandComments.setText(getString(R.string.show_comments));
		                    		flag = true;
	    	            		}
	    	            	}
	    	               	break;
                        case R.id.share:
                            Intent intent = new Intent(Intent.ACTION_SEND);
                            intent.setType("text/plain");
                            intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.dirtyComments)+Integer.toString(postID));
                            startActivity(Intent.createChooser(intent, "Поделиться постом"));
                            break;
                        case R.id.browser:
                            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.dirtyComments)+Integer.toString(postID)));
                            startActivity(browserIntent);
                            break;

    	            }
    	        }
    	 };
    	 
    	 img.setOnClickListener(buttonsListen);
    	 expandComments.setOnClickListener(buttonsListen);
         share.setOnClickListener(buttonsListen);
        openPost.setOnClickListener(buttonsListen);
    	 
        list.addHeaderView(headerView, null, true);

 		 ArrayList<CommentsItem> data = new ArrayList<CommentsItem>();
 		 adapter = new CommentsListAdapter(this, data );
    	 list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.w("item click:","item click");
                String url = ((CommentsItem)adapterView.getItemAtPosition(i)).getAboutUser();
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://dirty.ru"+url));
                startActivity(browserIntent);
            }
        });

    }
    

    protected class InitTask extends AsyncTask<String, Integer, String>{
 		private ArrayList<CommentsItem> data = new ArrayList<CommentsItem>();
        @Override
        protected void onPreExecute() 
        {
        	super.onPreExecute();
     		commentsLoadingBar.setVisibility(View.VISIBLE);
        }
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
				new DataParse().parseComments(params[0],data);}
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
			return "Complete";
		}
		
        @Override
        protected void onPostExecute(String result) 
        {
            super.onPostExecute(result);
            if(result == null)
            {
            	commentsLoadingBar.setVisibility(View.GONE);
            	commentsAttention.setVisibility(View.VISIBLE);
            	
            }
            for(int i=0;i<data.size();i++)
            	adapter.add(data.get(i));

            adapter.notifyDataSetChanged();
            commentsLoadingBar.setVisibility(View.GONE);
        }
    	
    }

}
